const initialState = {
  channel_id: 0,

  /** 全部的频道列表 */
  allList: [] as ChannelType[],

  /** 用户的频道列表 */
  userList: [] as ChannelType[],
};

export default function channelReducer(
  state = initialState,
  action: ChannelActionType
): typeof initialState {
  switch (action.type) {
    case 'channel/saveChannels':
      return {
        ...state,
        allList: action.payload,
      };
    case 'channel/saveUserChannels':
      return {
        ...state,
        userList: action.payload,
      };
    case 'channel/updateUserChannels':
      return {
        ...state,
        userList: [...state.userList, action.payload],
      };
    case 'channel/delUserChannels':
      return {
        ...state,
        userList: state.userList.filter((v) => v.id !== action.payload),
      };
    case 'channel/setChannelId':
      return {
        ...state,
        channel_id: action.payload,
      };

    default:
      return state;
  }
}

export type ChannelType = {
  id: number;
  name: string;
};

export type ChannelActionType =
  | { type: 'channel/saveChannels'; payload: ChannelType[] }
  | { type: 'channel/saveUserChannels'; payload: ChannelType[] }
  | { type: 'channel/updateUserChannels'; payload: ChannelType }
  | { type: 'channel/delUserChannels'; payload: number }
  | { type: 'channel/setChannelId'; payload: number };
